# coding=utf-8
from django.db import models

# Create your models here.
from extras.const import SEND_TYPES


class ESBRecord(models.Model):
    """
    网关接口记录
    """
    send_type = models.SmallIntegerField(default=SEND_TYPES.SEND_WEIXIN, verbose_name=u'发送类型')
    content = models.TextField(verbose_name=u'消息内容')
    platform_code = models.CharField(max_length=216, blank=True, default='', verbose_name=u'平台编码')
    is_close = models.BooleanField(default=False, verbose_name=u'是否关闭')
    receivers = models.CharField(max_length=1024, default='', verbose_name=u'接受者')
    is_success = models.BooleanField(default=True, verbose_name=u'是否成功')
    fail_reason = models.TextField(null=True, blank=True, default='', verbose_name=u'失败原因')
    create_time = models.DateTimeField(u'创建时间', auto_now_add=True)

    class Meta:
        ordering = ('-id',)

    def to_dict(self):
        """重写model_to_dict()方法转字典"""
        from datetime import datetime

        opts = self._meta
        data = {}
        for f in opts.concrete_fields:
            value = f.value_from_object(self)
            if isinstance(value, datetime):
                value = value.strftime('%Y-%m-%dT%H:%M:%SZ')
            elif isinstance(f, models.FileField):
                value = value.url if value else None
            data[f.name] = value
        return data
